//路由驱动文件
export default function router(routesRules) {
  /**
   console.log(routesRules);
   * [
   *   {
         path: '/detail/:id',
         view: DetailView,
         script: ''
       },
       {
         path: '/',
         view: HomeView,
         script: ''
       }
   * ]
   */

  //页面加载的事件处理程序函数
  function handleLoadView() {
    //路径分析匹配参数
    //http://localhost:5173/#/detail/:id/:num
    //http://localhost:5173/#/detail/1001/4

    //获取url地址栏上的信息对象
    const pathInfo = getRouteInfo(location.hash);
    // console.log(pathInfo);
    //{viewName: 'detail', params: ['1001', '4']}
    routesRules.forEach(async (item) => {
      //自定义路由规则对象集合上的信息对象
      const routeInfo = getRouteInfo('#' + item.path);
      // console.log(routeInfo);
      //{viewName: 'detail', params: ['id']}
      //{viewName: 'home', params: []}

      //假如自定义路由规则对象里的名称与url地址栏对象里的名称一致时说明是同一页面时
      if (routeInfo.viewName === pathInfo.viewName) {
        const params = {};
        routeInfo.params.map((routeItem, routeIndex) => {
          pathInfo.params.map((pathItem, pathIndex) => {
            if (routeIndex === pathIndex) {
              params[routeItem] = pathItem;
            }
          });
        });
        // console.log(params);
        //{id: 1001}

        // console.log(this);
        // <div id="app"></div>
        //item.view(params) 即执行 与后端请求数据拼接好的视图模版函数 执行后渲染页面
        this.innerHTML = await item.view(params);
        item.script();
      }
    });
  }

  //获取地址栏中的name和参数集合信息
  function getRouteInfo(hash) {
    // console.log(location.hash);
    //假如分析 #/detail/1
    const pathItems = hash
      .substring(1)
      .split('/')
      .filter((item) => item !== '');
    // console.log(hash.substring(1));
    // /detail/1
    // console.log(hash.substring(1).split('/'));
    //['', 'detail', '1']
    // console.log(pathItems);
    //['detail', '1']

    //假如分析 #/detail/:id/:num
    const params = pathItems.slice(1).map((item) => item.replace(':', ''));
    // console.log(pathItems.slice(1));
    //[':id', ':num']
    // console.log(pathItems.slice(1).map((item) => item.replace(':', '')));
    //['id', 'num']

    return {
      viewName: pathItems[0] || 'home', //detail
      params: params //['id', 'num']
    };
  }

  //返回一个函数 供外部执行时传入根节点#app
  return function (el) {
    // console.log(el);
    //<div id="app"></div>
    //页面首次加载时和地址栏hash变化时执行
    window.addEventListener('load', handleLoadView.bind(el), false);
    window.addEventListener('hashchange', handleLoadView.bind(el), false);
  };
}
